import { Fragment, useMemo } from 'react';
import { Button, Col, Form, Input, Row, Select, Space, Table, TreeSelect } from 'antd';
import { onMouseOutBtn } from '@/utils';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import Cls from 'classnames';
import { commonPageSizeOptions, showTotalInfo } from '@/common/constVariable';

export const UpdateTableCommon: React.FC<any> = ({ searchProps, selectTablePorps, tableProps, styleFixCls }) => {
  /** 获取表格参数 */
  const { onPageChange, pagination, rowKey = 'id', tableTotalShow } = tableProps;

  /** 获取组件头部操作 */
  const { onReset, onSearch, searchList } = searchProps;

  /** 从表格操作取值  notCreditIDList:只给合同主体使用 */
  const { selectType = 'radio', selectRowObjList, onSelectTable, setCheckRows, getCheckboxProps, notCreditIDList } = selectTablePorps;

  /** 搜索表单form */
  const [searchForm] = Form.useForm();

  /** 搜索 */
  const searchManage = () => {
    const searchValues: Record<string, any> = searchForm?.getFieldsValue();
    onSearch({ ...searchValues, ...pagination });
  };

  /** 重置 */
  const reloadManage = () => {
    searchForm?.resetFields();
    onReset({ ...pagination });
  };

  /** 单选 */
  const onSelectRadio = (selectRow: Record<string, any>, selected: boolean) => {
    if (selectType == 'radio') {
      onSelectTable(selected ? [{ ...selectRow }] : {});
    } else if (selectType == 'checkbox') {
      if (selected) {
        let selectList: Record<string, any>[] = [...selectRowObjList];
        selectList?.push({ ...selectRow });
        onSelectTable(selectList);
      } else {
        let selectList: Record<string, any>[] = selectRowObjList?.filter((item: any) => item?.[rowKey] != selectRow?.[rowKey]);
        onSelectTable(selectList);
      }
    }
  };

  /** 多选全选 */
  const onSelectCheckAll = (selected: boolean, selectedRows: Record<string, any>[], changeRows: Record<string, any>[]) => {
    if (selectType == 'checkbox') {
      if (selected) {
        let selectList: Record<string, any>[] = [...selectRowObjList, ...changeRows];
        onSelectTable(selectList);
      } else {
        const changeKeys: string[] = changeRows?.map((itemChange: any) => itemChange?.id);
        let selectList: Record<string, any>[] = selectRowObjList?.filter((item: any) => !changeKeys?.includes(item?.[rowKey]));
        onSelectTable(selectList);
      }
    }
  };

  /** 多选 */
  const onChangeCheckBox = (selectedRowKeys: React.Key[], selectedRows: Record<string, any>[]) => {
    // if (selectType == 'checkbox') {
    //   onSelectTable(selectedRows, selectedRowKeys);
    // }
  };

  /** 处理选中数据 */
  const selectRowKeys = useMemo(() => {
    if (selectRowObjList) {
      let selectKeys: string[] = [];
      selectRowObjList?.forEach((item: any) => {
        selectKeys?.push(item?.oppositeID ? item?.oppositeID : item?.[rowKey]);
      });
      return selectKeys;
    }
    return [];
  }, [selectRowObjList]);

  return (
    <div className={`${styleFixCls}updateStepsBox`}>
      <div className={`${styleFixCls}updateStepsBox-searchForm`}>
        <div className={`${styleFixCls}updateStepsBox-searchForm-leftForm`}>
          <Form form={searchForm}>
            <Row gutter={[8, 8]}>
              {searchList?.map((item: any, index: number) => {
                if (!item?.whetherSenior && item?.componentType != 'QueryParams') {
                  return (
                    <Col md={item?.md} sm={item?.sm} key={index}>
                      <Form.Item name={item?.name}>
                        {item?.componentType == 'Input' ? (
                          <Input placeholder={item?.placeholder} allowClear={item?.allowClear} />
                        ) : item?.componentType == 'Select' ? (
                          <Select placeholder={item?.placeholder} allowClear={item?.allowClear}>
                            {item?.dataSource?.map((itemChil: any) => {
                              return (
                                <Select.Option value={itemChil?.value} key={itemChil?.value}>
                                  {itemChil?.name}
                                </Select.Option>
                              );
                            })}
                          </Select>
                        ) : item?.componentType == 'TreeSelect' ? (
                          <TreeSelect
                            placeholder={item?.placeholder}
                            showSearch={item?.showSearch}
                            treeNodeFilterProp={item?.treeNodeFilterProp}
                            allowClear={item?.allowClear}
                            fieldNames={item?.fieldNames}
                            treeData={item?.dataSource}
                          />
                        ) : (
                          <></>
                        )}
                      </Form.Item>
                    </Col>
                  );
                } else {
                  return <Fragment key={index} />;
                }
              })}
            </Row>
          </Form>
        </div>
        <div className={`${styleFixCls}updateStepsBox-searchForm-rightBtn`}>
          <Space>
            <Button type={'primary'} icon={<SearchOutlined />} onMouseOut={onMouseOutBtn} onClick={searchManage}>
              查询
            </Button>
            <Button type={'default'} icon={<ReloadOutlined />} onMouseOut={onMouseOutBtn} onClick={reloadManage}>
              重置
            </Button>
          </Space>
        </div>
      </div>
      <div className={Cls('list-table', `${styleFixCls}updateStepsBox-tableBox`)}>
        <Table
          size="small"
          bordered
          scroll={{ x: 1200, y: 'true' }}
          columns={tableProps?.columns}
          loading={tableProps?.loading}
          dataSource={tableProps?.dataSource}
          rowKey={rowKey}
          rowSelection={{
            type: selectType,
            selectedRowKeys: selectRowKeys,
            onSelect: onSelectRadio,
            onChange: onChangeCheckBox,
            onSelectAll: onSelectCheckAll,
            getCheckboxProps: getCheckboxProps ? getCheckboxProps : () => {},
          }}
          onRow={(record) => {
            return {
              onClick: (event) => {
                event.stopPropagation();
                if (!(notCreditIDList && notCreditIDList?.length > 0 && notCreditIDList?.includes(record?.creditID))) {
                  if (selectType == 'radio') {
                    onSelectRadio(record, !selectRowKeys?.includes(record?.[rowKey]));
                  } else if (selectType == 'checkbox') {
                    const selectKeys: React.Key[] = selectRowObjList?.map((item: any) => item?.[rowKey]);
                    if (selectKeys?.includes(record?.[rowKey])) {
                      const onlySelectRows = selectRowObjList?.filter((item: any) => item?.[rowKey] != record?.[rowKey]);
                      const onLySelectKeys = selectKeys?.filter((item: any) => item != record?.[rowKey]);
                      onChangeCheckBox(onLySelectKeys, onlySelectRows);
                    } else {
                      const newSelectRows = [...selectRowObjList];
                      newSelectRows?.push(record);
                      const newSelectKeys: React.Key[] = [...selectKeys];
                      newSelectKeys?.push(record?.[rowKey]);
                      onChangeCheckBox(newSelectKeys, newSelectRows);
                    }
                  }
                }
              },
            };
          }}
          pagination={{
            ...pagination,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: commonPageSizeOptions,
            showTotal: tableTotalShow ? tableTotalShow : showTotalInfo,
            onChange: onPageChange,
            // pageSize: pagination?.pageSize,
            // current: pagination?.current,
          }}
        />
      </div>
    </div>
  );
};
